package br.com.despesasPlan.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import br.com.despesasPlan.sql.GenericSql;

public class UtilDao extends GenericDao{
	public void executeSql(String sql, ArrayList<Object> params) {
		int index = 1;
		try {
			PreparedStatement stmt = getConnection().prepareStatement(sql);
			for (Object o: params) {
				stmt.setObject(index++, o);
			}
			stmt.execute();
			stmt.close();
		} catch (SQLException e) {
			throw new RuntimeException("Erro a executar comando: "+e.getMessage());
		}
	}
	
	public ResultSet executeQuerySql(String sql, ArrayList<Object> params) {
		ResultSet rs;
		int index = 1;
		try {
			PreparedStatement stmt = getConnection().prepareStatement(sql);
			if (params != null) {
			for (Object o: params) {
				stmt.setObject(index++, o);
			}
			}
			rs = stmt.executeQuery();
			stmt.execute();
			stmt.close();
		} catch (SQLException e) {
			throw new RuntimeException("Erro a executar comando: "+e.getMessage());
		}
		return rs;
	}
	
	public long getProximoCodigo(String tabela) {
		String sqlProximoCodigo = GenericSql.getSqlProximoCodigo(tabela);
		long id = 0;
		try {
			ResultSet rs = executeQuerySql(sqlProximoCodigo, null);
			while (rs.next()) {
				id = rs.getLong(1);
			}
		} catch (SQLException e) {
			throw new RuntimeException("Erro ao buscar o próximo código: "+e.getMessage());
		}
		return id + 1;
	}
}
